package com.example.blogapi.service;

import com.example.blogapi.dao.TagDao;
import com.example.blogapi.model.Tag;

import java.sql.SQLException;
import java.util.List;

public class TagService {
    private final TagDao tagDao;

    public TagService() {
        this.tagDao = new TagDao();
    }

    public List<Tag> getAllTags() throws SQLException {
        return tagDao.findAll();
    }

    public Tag getTagById(Long id) throws SQLException {
        return tagDao.findById(id);
    }

    public Tag createTag(Tag tag) throws SQLException {
        // 检查标签名是否已存在
        Tag existingTag = tagDao.findByName(tag.getName());
        if (existingTag != null) {
            throw new IllegalArgumentException("Tag name already exists");
        }
        
        return tagDao.create(tag);
    }

    public Tag updateTag(Long id, Tag tag) throws SQLException {
        Tag existingTag = tagDao.findById(id);
        if (existingTag == null) {
            throw new IllegalArgumentException("Tag not found");
        }

        // 如果标签名已更改，检查新标签名是否已存在
        if (!existingTag.getName().equals(tag.getName())) {
            Tag tagWithSameName = tagDao.findByName(tag.getName());
            if (tagWithSameName != null) {
                throw new IllegalArgumentException("Tag name already exists");
            }
        }

        tag.setId(id);
        tag.setCreatedAt(existingTag.getCreatedAt());
        return tagDao.update(tag);
    }

    public boolean deleteTag(Long id) throws SQLException {
        Tag existingTag = tagDao.findById(id);
        if (existingTag == null) {
            throw new IllegalArgumentException("Tag not found");
        }
        
        return tagDao.delete(id);
    }
}